package com.fx.easyexcel.demo.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fx.easyexcel.demo.pojo.Examiner;
import com.fx.easyexcel.demo.util.IdUtil;
import com.fx.easyexcel.demo.util.TimeUtil;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.*;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Faxon
 * @version 1.0
 * @date 2020-07-03 23:33
 **/
@Service
public class ReadExcelToPdfService {

    private static final Logger LOGGER = LoggerFactory.getLogger(ReadExcelToPdfService.class);

    @Value("${output.pdfPath}")
    public String outputPath;

    @Value("${output.pdfSuffix}")
    public String suffix;

    ObjectMapper objectMapper = new ObjectMapper();

    private int i = 1;

    public void readDate(List<Examiner> examinerList) {
        examinerList.forEach(this::toPdf);
    }

    public void toPdf(Examiner examiner) {
        if (examiner == null || StringUtils.isBlank(examiner.getName()) || StringUtils.isBlank(examiner.getIdNumber())) {
            return;
        }
        //设置数据
        Map<String, String> datemap = new HashMap<>(16);
        datemap.put("name", examiner.getName());
        datemap.put("zkzh", IdUtil.getZkzh(examiner.getExamsDate(), i++));
        datemap.put("idNumber", examiner.getIdNumber());
        // 模板路径
        String templatePath = "/template/template.pdf";
        // 生成的新文件路径
        try {
            FileUtils.forceMkdir(new File(outputPath));
        } catch (IOException e) {
            e.printStackTrace();
        }
        String newPDFPath = outputPath + examiner.getName() + "-" + examiner.getIdNumber() + suffix;
        PdfReader reader = null;
        PdfStamper stamper = null;
        Document doc = null;
        PdfCopy copy = null;
        try (
                FileOutputStream out = new FileOutputStream(newPDFPath);
                ByteArrayOutputStream bos = new ByteArrayOutputStream()
        ) {
            BaseFont bf = BaseFont.createFont("/template/simsun.ttc,0", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            //读取pdf模板
            reader = new PdfReader(templatePath);
            stamper = new PdfStamper(reader, bos);
            AcroFields form = stamper.getAcroFields();
            form.addSubstitutionFont(bf);
            for (String key : datemap.keySet()) {
                String value = datemap.get(key);
                form.setField(key, value);
            }
            //如果为false，生成的PDF文件可以编辑，如果为true，生成的PDF文件不可以编辑
            stamper.setFormFlattening(true);
            stamper.close();

            doc = new Document();
            copy = new PdfCopy(doc, out);
            doc.open();
            PdfImportedPage importPage = null;
            ///循环是处理成品只显示一页的问题
            for (int i = 1; i <= reader.getNumberOfPages(); i++) {
                importPage = copy.getImportedPage(new PdfReader(bos.toByteArray()), i);
                copy.addPage(importPage);
                importPage.closePath();
            }
            doc.close();
            copy.close();
            reader.close();
        } catch (IOException | DocumentException e) {
            LOGGER.error("Message：[{}]，Time：[{}},Class:[{}]", examiner.getIndex() + examiner.getName() + "生成Pdf失败",
                    TimeUtil.getNowTime(), this.getClass().getName());
        }
    }

}
